<template>
    <view class="paddingY30 poster" style="width: 0px; height: 0px; overflow: hidden">
        <canvas
            type="2d"
            width="315"
            height="485"
            style="width: 315px: height: 485px margin:0 auto"
            id="myCanvas"
        ></canvas>
    </view>
</template>

<script>
import resource from '@/utils/resource'
import ossurl from '@/utils/ossurl'
import { WX_APP_ID } from '@/utils/config'
import canvasUtil from '../../utils/canvas'

export default {
    props: {
        imgs: Array,
        page: String,
        scene: String,
        tip: String,
        userId: String
    },
    data() {
        return {
            filePath: ''
        }
    },
    methods: {
        share() {
            if (this.filePath) {
                this.beginDraw(this.filePath)
                return
            }
            this.getQrcode((buffer) => {
                const qrCodeFile = wx.env.USER_DATA_PATH + '/temp_image.jpeg'
                const fsm = uni.getFileSystemManager()
                fsm.writeFile({
                    filePath: qrCodeFile,
                    data: buffer,
                    encoding: 'binary',
                    success: (res) => {
                        this.filePath = qrCodeFile
                        this.beginDraw(this.filePath)
                    },
                    complete: () => {
                        uni.hideLoading()
                    }
                })
            })
        },

        getQrcode(callback) {
            uni.showLoading({
                title: '加载中...'
            })
            var scene = this.scene + ':' + this.userId
            let url = `${this.$service.base.apis.MiNI_CODE}?clientId=${WX_APP_ID}&wxaCodeUnlimitBytesRequest.scene=${scene}&envVersion=trial`
            url += `&wxaCodeUnlimitBytesRequest.page=${encodeURIComponent(this.page)}`
            wx.request({
                url,
                method: 'get',
                responseType: 'arraybuffer',
                header: {
                    track: JSON.stringify({
                        os: 4,
                        bundleId: 'com.supermart.mart',
                        clientId: WX_APP_ID
                    })
                },
                success: (res) => {
                    if (res.statusCode == 200 && res.data && res.data.byteLength > 0) {
                        callback(res.data)
                    } else {
                        uni.hideLoading()
                    }
                },
                fail: (err) => {
                    uni.hideLoading()
                }
            })
        },
        beginDraw(qrCodeFile) {
            const query = wx.createSelectorQuery().in(this)
            query
                .select('#myCanvas')
                .fields({ node: true, size: true })
                .exec((res) => {
                    const canvas = res[0].node

                    canvas.width = 945
                    canvas.height = 1455

                    this.draw(canvas, canvas.width, canvas.height, qrCodeFile)
                })
        },
        draw(canvas, width, height, qrCodeFile) {
            const ctx = canvas.getContext('2d')
            ctx.clearRect(0, 0, canvas.width, canvas.height)

            canvasUtil.circleImg(ctx, null, 0, 0, width, height, 24)

            let bgImg = canvas.createImage()
            bgImg.src = ossurl.common.posterBg
            bgImg.onload = (e) => {
                canvasUtil.circleImg(ctx, bgImg, 0, 0, width, height, 24)
                // canvasUtil.drawOneText(
                //     ctx,
                //     '长摁识别小程序码 去超级玛特领手办吧',
                //     'normal bold 33px Arial',
                //     '#fff',
                //     width,
                //     1400
                // )

                let qrCode = canvas.createImage()
                qrCode.src = qrCodeFile
                qrCode.onload = (e) => {
                    canvasUtil.circleImg(ctx, qrCode, (width + 260) / 2, 1155, 185, 185, 76)
                }

                // canvasUtil.drawOneText(ctx, this.tip, 'normal bold 48px Arial', '#fff', width, 1020)

                // this.drawImgs(canvas, ctx)

                uni.showLoading({
                    title: '绘制中...'
                })
                let time = 1300 + this.imgs.length * 100
                time = time > 2000 ? 2000 : time
                setTimeout(() => {
                    wx.canvasToTempFilePath({
                        canvas,
                        success: (res) => {
                            // 生成的图片临时文件路径
                            const tempFilePath = res.tempFilePath
                            wx.showShareImageMenu({
                                path: tempFilePath,
                                success: (res) => {
                                    this.$emit('success')
                                },
                                fail: (err) => {
                                    console.log(err)
                                }
                            })
                        },
                        complete: () => {
                            uni.hideLoading()
                        }
                    })
                }, time)
            }
        },
        drawImgs(canvas, ctx) {
            let w = 255
            let h = 300
            let imageW = 0
            let imageH = 0
            if (this.imgs.length === 1) {
                w = 382
                h = 450
                imageW = w - 44
                imageH = h - 112

                this.drawImgItem(canvas, ctx, this.imgs[0].cover, w, h, 282, 386, imageW, imageH)
            } else if (this.imgs.length === 2) {
                w = 331
                h = 390
                imageW = w - 40
                imageH = h - 96

                this.drawImgItem(canvas, ctx, this.imgs[0].cover, w, h, 111, 416, imageW, imageH)
                this.drawImgItem(canvas, ctx, this.imgs[1].cover, w, h, 503, 416, imageW, imageH)
            } else {
                imageW = w - 30
                imageH = h - 74
                this.drawNormals(canvas, ctx, w, h, imageW, imageH)
            }
        },
        drawNormals(canvas, ctx, w, h, imageW, imageH) {
            let datas = []
            switch (this.imgs.length) {
                case 3:
                    datas = [this.imgs]
                    break
                case 4:
                    datas = [this.imgs.slice(0, 2), this.imgs.slice(2)]
                    break
                case 5:
                    datas = [this.imgs.slice(0, 3), this.imgs.slice(3)]
                    break
                case 6:
                    datas = [this.imgs.slice(0, 3), this.imgs.slice(3)]
                    break
            }
            for (let row = 0; row < datas.length; row++) {
                let top = 0
                if (datas.length === 1) {
                    top = 461
                } else {
                    top = 296 + row * (h + 30)
                }
                this.drawRow(canvas, ctx, datas[row], w, h, imageW, imageH, top)
            }
        },
        drawRow(canvas, ctx, data, w, h, imageW, imageH, top) {
            let beginLeft = data.length === 2 ? 203 : 60
            for (let i = 0; i < data.length; i++) {
                let left = beginLeft + i * (w + 30)
                this.drawImgItem(canvas, ctx, data[i].cover, w, h, left, top, imageW, imageH)
            }
        },
        drawImgItem(canvas, ctx, src, w, h, left, top, imageW, imageH) {
            let wrapper = canvas.createImage()
            wrapper.src = resource.poster_imgW
            wrapper.onload = (e) => {
                canvasUtil.circleImg(ctx, wrapper, left, top, w, h, 10)

                wx.getImageInfo({
                    src: src,
                    success: (res) => {
                        let wRatio = res.width / imageW
                        let ratioHeight = res.height / wRatio
                        //如果按比例后高度 大于 最大高度，那么安高的比例来
                        if (ratioHeight > imageH) {
                            imageH = imageH
                            imageW = res.width / (res.height / imageH)
                        } else {
                            imageW = imageW
                            imageH = res.height / (res.width / imageW)
                        }

                        let img = canvas.createImage()
                        img.src = res.path
                        img.onload = (e) => {
                            canvasUtil.circleImg(
                                ctx,
                                img,
                                left + (w - imageW) / 2,
                                top + (h - imageH) / 2,
                                imageW,
                                imageH,
                                0
                            )
                        }
                    }
                })
            }
        }
    }
}
</script>

<style lang="scss">
.poster {
    canvas {
        height: 380px !important;
    }
}
</style>